<template>
    <div class="main">
        <el-form ref="ruleFormRef" :model="form" :rules="rules" class="login-box" label-position="right"
            label-width="80px" status-icon>
            <h3 class="login-title">{{ model == 'login' ? '欢迎登陆' : '用户注册' }}</h3>
            <el-form-item label="用户名" prop="username">
                <el-input type="text" placeholder="请输入用户名" v-model.trim="form.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" v-if="model != 'login'">
                <el-input type="text" placeholder="请输入邮箱" v-model.trim="form.email"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" placeholder="请输入密码" v-model.trim="form.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="repassword" v-if="model != 'login'">
                <el-input type="repassword" placeholder="请再次输入密码" v-model.trim="form.repassword" show-password>
                </el-input>
            </el-form-item>

            <el-form-item label-width="20px">
                <el-button type="primary" @click="submitForm(ruleFormRef)" style="margin-left: 90px">{{ model == 'login'
                        ? '登陆' : '注册'
                }}
                </el-button>
                <el-button type="info" @click="resetForm(ruleFormRef)" style="margin-left: 50px">重置</el-button>
                <a @click.prevent="changeModel">{{ model == 'login' ? '注册' : '登陆' }}</a>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
    import { reactive, ref, onMounted } from 'vue'
    import type { FormInstance, FormRules } from 'element-plus'
    import { ElMessage } from 'element-plus'
    import { useRouter } from 'vue-router'
    import link from '../../api/link.js'
    
const router = useRouter()

//注册登陆状态
const model = ref('login')
//表单内容
let form = ref({
    username: '',
    password: '',
    repassword: '',
    email: ''
})

const ruleFormRef = ref<FormInstance>()

onMounted(() => {
    console.log(process.env.VUE_APP_API);
})

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//自定义确认密码验证规则
const checkRePsw = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码！'))
    } else if (value != form.value.password) {
        callback(new Error('两次输入的密码不一致！'))
    } else {
        callback()
    }
}

//自定义邮箱验证规则
const checkEmail = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入邮箱！'))
    } else if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(value))) {
        callback(new Error('请输入正确格式的邮箱！'))
    } else {
        callback()
    }
}


//表单验证规则
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '用户名不能为空！', trigger: 'blur' },
        { min: 4, max: 8, message: '请输入4~8位用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码不能为空！', trigger: 'blur' },
        { min: 6, max: 12, message: '请输入6~12位密码！', trigger: 'blur' },
    ],
    repassword: [
        { required: true, validator: checkRePsw, trigger: 'blur' },
    ],
    email: [
        { required: true, validator: checkEmail, trigger: 'blur' },
    ],
})


//切换注册登陆
const changeModel = () => {
    model.value = model.value == 'login' ? 'register' : 'login'
    resetForm(ruleFormRef.value)
}

//表单提交
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (!valid) {
            console.log('error submit!')
            return false
        }

        if (model.value === 'login') {
            //登陆
            console.log('login!')

            link(`/register?username=${form.value.username}&password=${form.value.password}`).then((res) => {
                console.log(res);
                let { data } = res
                if (data.length != 0) {
                    ElMessage({
                        message: '登陆成功！',
                        type: 'success',
                    })
                    resetForm(ruleFormRef.value)

                    let obj = {
                        id: data[0].id,
                        username: data[0].username,
                        power: data[0].power
                    }
                    localStorage.setItem('user', JSON.stringify(obj))
                    router.push('/home')
                } else {
                    ElMessage({
                        message: '用户名或密码错误！',
                        type: 'error',
                    })
                }
            })
        } else {
            //注册
            let data = {
                "username": form.value.username,
                "password": form.value.password,
                "email": form.value.email,
                "power": []
            }
            link('/register', "POST", data).then((res) => {
                console.log(res.status);
                let { data } = res
                if (Object.keys(data).length != 0) {
                    ElMessage({
                        message: '注册成功！',
                        type: 'success',
                    })
                    changeModel()
                } else {
                    ElMessage({
                        message: '注册失败！',
                        type: 'error',
                    })
                }
            })
        }

    })



}
</script>

<style lang="scss" scoped>
.main {
    height: 100vh; 
    overflow: hidden;

    .login-title {
        text-align: center;
        margin-bottom: 20px;
        font-size: 20px;
    }

    .login-box {
        width: 400px;
        margin: 120px auto;
        border: 1px solid #dcdfe6;
        padding: 30px 55px 10px 20px;
        border-radius: 5px;
        box-shadow: 0 0 30px #dcdfe6;

        .el-button--info {
            margin-left: 60px;
        }
    }




    a {
        position: absolute;
        right: 2px;
        text-decoration: underline;
        color: #409eff;
        cursor: pointer;
    }
}
</style>